﻿window.ErrorPageView = Backbone.View.extend({
    el: '#jqt',
    initialize: function () {
        this.template = $('#ErrorPageTemplate').html();
    },

    render: function () {
        this.$el.append(Mustache.render(this.template, [], []));
        return this;
    }
});

var route = [
{ pageId: "Login", viewClass: LoginView }
, { pageId: "Register", viewClass: RegisterView }
, { pageId: 'Agreement',viewClass:AgreementView }
, { pageId: "Catalog", viewClass: CatalogView }
, { pageId: "FirstCategory", viewClass: FirstLevelView }
, { pageId: 'SecondCategory', viewClass: SecondLevelView }
, { pageId: 'ThirdCategory', viewClass: ThirdLevelView }
, { pageId: "ProductList", viewClass: ProductListView }
, { pageId: 'ProductDetail', viewClass: ProductDetailView }
, { pageId: 'MyCart', viewClass: MyCartView }
, { pageId: 'MyUserInfo', viewClass: UserInfoView }
, { pageId: 'OrderMake', viewClass: MakeOrderView }
, { pageId: 'MyCollect', viewClass: MyCollectView }
, { pageId: 'MyOrder', viewClass: MyOrderListView }
, { pageId: 'SearchList', viewClass: SearchListView }
, { pageId: 'MyFilter', viewClass: MyFilterView }
, { pageId: 'MyMessage', viewClass: MessageView }
, { pageId: 'AddressList', viewClass: AddressListView }
, { pageId: 'PaymentList', viewClass: PaymentView }
, { pageId: 'DispatchModeList', viewClass: DispatchView }
, { pageId: 'MyInvoice', viewClass: InvoiceView }
, { pageId: 'CouponList', viewClass: CouponView }
, { pageId: 'GenerateOrder', viewClass: OrderGenerateView }
, { pageId: 'OrderDetail', viewClass: OrderDetailView }
, { pageId: 'PayDetail', viewClass: PayDetailView }
, { pageId: 'ErrorPage', viewClass: ErrorPageView }
];

window.Page = Backbone.Model.extend({
    defaults: {
        pageId: "Login",
        viewClass: LoginView
    }
});

window.PageCollection = Backbone.Collection.extend({
    model: Page
});

window.PageView = Backbone.View.extend({
    el: "#jqt",
    model: Page,

    events: {
        'click .registerLink,.foot_register': 'renderRegister',
        'click .foot_login,.link-btn[action="avatar"],.list li[action="myhome"],.foot_user': 'renderMyInfo',
        'click .link-btn[action="home"]': 'renderDefaultPage',
        'click .list li[action="categorys"],.link-btn[action="sort"]': 'renderFirstCategory',
        'click .list li[action="collect"]': 'renderMyCollect',
        'click .link-btn[action="cart"],.list li[action="buyer"]': 'renderMyCart',
        'click .list li[action="message"]': 'renderMyMessage',
        'click .list li[action="order"]': 'renderMyOrder',
        'click .foot_exit': 'logout',
        'click .header .back': 'goBack',
        'click .footer .to-top': 'scrollToTop'
    },
    render: function () {

        pageRoute.navigate('page/' + this.model.get("pageId"));

        return this;
    },

    renderContent: function (viewType) {
        var pageId = this.model.get('pageId');

        if (this.$el.find('#' + pageId).length > 0) {
            $('#' + pageId).remove();
        }
        if (viewType && typeof viewType === "function") {
            var view = new viewType({ id: pageId + '12' });
            view.render();
        } //append div into jqt

        this.render(); //register route
    },

    renderDefaultPage: function () {

        this.goTo('Catalog');
    },

    renderMyInfo: function () {
        if (this.getCookieValue('uid'))
            this.goTo('MyUserInfo');
        else this.goTo('Login');
    },

    

    renderRegister: function () {
        this.goTo('Register');
    },

    renderFirstCategory: function () {
        this.goTo('FirstCategory');
    },

    renderMyCart: function () {
        if (this.getCookieValue('uid'))
            this.goTo('MyCart');
        else {
            this.goTo('Login');
            localStorage.setItem('loginfrom', 'fetchCart');
        }
    },

    renderMyCollect: function () {
        if (this.getCookieValue('uid'))
            this.goTo('MyCollect');
        else {
            this.goTo('Login');
            localStorage.setItem('loginfrom', 'myCollect');
        }
    },

    renderMyMessage: function () {
        localStorage.setItem('messagePageIndex', 1);
        if (this.getCookieValue('uid'))
            this.goTo('MyMessage');
        else {
            this.goTo('Login');
            localStorage.setItem('loginfrom', 'myMessage');
        }
    },

    renderMyOrder: function () {
        if (this.getCookieValue('uid'))
            this.goTo('MyOrder');
        else {
            this.goTo('Login');
            localStorage.setItem('loginfrom', 'myOrder');
        }
    },

    goTo: function (pageId) {
        var p = _.find(pageList.toArray(), function (model) {
            return model.get('pageId') === pageId;
        });
        page.set(p.toJSON());

        var viewType = page.get('viewClass');

        this.renderContent(viewType);

        var fromPage = this.$el.find('.current');
        var toPage = $('#' + pageId);
        var animation = { name: 'slideleft', selector: '.slideleft, .slide, #jqt > * > ul li a' };

        if (fromPage.length !== 0) {
            jQT.doNavigation(fromPage, toPage, animation);
        }

        toPage.addClass('current');

        this.changeFoot();

        this.changeCartIcon();

        this.registerScroll();
    },

    goBack: function () {
        window.history.back();
    },

    logout: function () {
        localStorage.clear();
        var username = this.getCookieValue('uid');
        localStorage.setItem('username', username);
        $.post('api/account/LogOut', { id: this.getCookieValue('uid') }, function () {
            pageView.goTo('Catalog');
        }, 'json');
    },

    scrollToTop: function () {
        if (this.myScroll && this.myScroll instanceof iScroll)
            this.myScroll.scrollTo(0, 0);
    },

    myScroll: {},

    registerScroll: function () {
        var that = this;

        if (that.myScroll && that.myScroll instanceof iScroll) {
            that.myScroll.destroy();
            that.myScroll = null;
        }

        that.myScroll = new iScroll(that.model.get("pageId") + "Wrapper", {
            onBeforeScrollStart: function (e) {
                var target = e.target;
                while (target.nodeType != 1) target = target.parentNode;
                var targetName = target.tagName.toLowerCase();
                if (targetName != 'select' && targetName != 'input' && targetName != 'textarea')
                    e.preventDefault();
            }, onScrollStart: function () {
                $(':focus').blur();
            }
        });
        that.myScroll._resize();
    },

    resizeScroll: function () {
        var that = this;
        window.setTimeout(function () {
            if (that.myScroll && that.myScroll instanceof iScroll) {
                that.myScroll._resize();
            }
        }, 300);
    },

    changeFoot: function () {
        var loginid = this.getCookieValue('uid');
        if (loginid) {
            $('.footer').find('.foot_1').removeClass('foot_login').addClass('foot_user').text(loginid);
            $('.footer').find('.foot_2').removeClass('foot_register').addClass('foot_exit').text('退出');
        } else {
            $('.footer').find('.foot_1').removeClass('foot_user').addClass('foot_login').text('登录');
            $('.footer').find('.foot_2').removeClass('foot_exit').addClass('foot_register').text('注册');
        }
    },

    changeCartIcon: function () {
        var hasCarts = localStorage.getItem('hasCarts'),
            icon = hasCarts == 'true' ? 'cartm' : 'cart';
        $('.header a[action="cart"]>img').attr('src', '/Content/Images/header/' + icon + '.png');
    },

    getCookieValue: function (key) {
        var cookie = document.cookie;
        if (navigator.cookieEnabled && cookie) {
            if (cookie.length == 0) return undefined;
            var value = _.find(cookie.split(';'), function (cook) {
                return cook.trim().split('=')[0] == key;
            });
            return value && value.trim().split('=')[1];
        } else return undefined;
    },

    cookieTimeoutAutoLogin: function () {
        if (this.getCookieValue('uid')) {
            var user = new AutoLoginModel({
                id: 1,
                loginid: this.getCookieValue('uid')
            });
            user.save('', '', {
                success: function (res) {

                }
            });
        }
    }
});

window.PageRoute = Backbone.Router.extend({
    routes: {
        "page/:pageId": "loadPage",
        "": "home"
    },
    home: function () {
        //render login content
        pageView.cookieTimeoutAutoLogin();
        pageView.renderDefaultPage();
    },
    loadPage: function (pageId) {
        pageView.goTo(pageId);
    }
});

var pageList = new PageCollection(route);